/**
 * 
 */
var _startX = 0; // mouse starting positions 
var _startY = 0; 
var _offsetX = 0; // current element offset 
var _offsetY = 0; 
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0; // we temporarily increase the z-index during drag
var _defPos = 0;
var _isTurned = {};
var _side = 0;
var _gameStatus = 0;
var _scroll=[];
function id(id) 
//Simplyfies selecting by ID
{ 
	return document.getElementById(id);
}
// Gives absolute position of the element
function locationFinder(obj)
{
	var curleft=0;
	var curtop=0;
	if (obj.offsetParent){
		do{
			curleft+=obj.offsetLeft;
			curtop+=obj.offsetTop;
		}while (obj=obj.offsetParent);
	}
	return [curleft,curtop];
}
//Changes position to fixed, preparing ship to be moved
function fixPosition(obj)
{
	var loc = locationFinder(obj);
	obj.style.position="fixed";
	obj.style.left=loc[0]+_scroll[0]+'px';
	obj.style.top=loc[1]+_scroll[1]+'px';
	_offsetX = loc[0];
	_offsetY = loc[1];
}
function placeShipToCell(element,target,isTurned,isFromLoad)
{
	var element = $(element);
	var target = $(target);
	element.css("position","absolute");
	if (isTurned==false || isTurned == null)
	{
		var marginTopTemp = String((target.height()-element.height())/2)+"px";
		element.css("margin-top",String(marginTopTemp));
		element.css("margin-left","-0.25em");
	}
	else
	{
		if (isFromLoad==true)
		{
			var tempSrcURL = $("#"+key).attr("src");
			tempSrcURL = tempSrcURL.split(".png")[0]+"Rot.png";
			var tempHeight = $("img#"+key).css("height");
			element.css("height",$("img#"+key).css("width"));
			element.css("width",tempHeight);
			element.attr("src",tempSrcURL);
		}
		var marginLeftTemp = String((target.width()-element.height())/2)+"px";
		element.css("margin-left",marginLeftTemp);
		element.css("margin-top","-0.25em");
	}
	element.appendTo(target);
}
function getScrolled()
//Returns the diffrence betwean absolute and relative top of the page(to take into account the scrolling)
{
	return [$("html").offset().left,$("html").offset().top];
}
function doBlink(object,times)
{
	for (i=0;i<=times;i++)
	{
		$(object).fadeOut(300).fadeIn(300);
	}
}
// Keerab laeva umber
function turnShipHelper(target,isTurned)
{
	if (isTurned== null || isTurned == false)
	{
		if ($.browser.webkit)
		{
			target.css("-webkit-transform-origin","9% 50%");
		}
		else
		{
			target.css("-moz-transform-origin","9% 50%");
		}
		target.rotate(90);
	}
	else
	{
		target.rotate(0);
	}
}
function turnShip(target)
{
	var targetId=target.id;
	var isTurned = _isTurned[targetId];
	var validationResult = validateFor90DegreeTurn(target,isTurned);
	if (validationResult[0]==true)
	{
		var parentNode = target.parentNode;
		var target = $(target);
		turnShipHelper(target,isTurned);
		if (isTurned==null || isTurned==false)
		{
			_isTurned[targetId]=true;
		}
		else
		{
			_isTurned[targetId]=null;
		}
		if (validationResult[1]!=null)
		{
			placeShipToCell(target,parentNode,_isTurned[targetId],false);	
			paint(validationResult[2],"#CCCCCC");
			paint(validationResult[1],"red");
		}
	}
	else
	{
		var ValidationOfPreviousPos = validator(validationResult[1],target,isTurned);
		paint(ValidationOfPreviousPos[1],"red");
		doBlink(target,1);
	}
		
}
function paint(arr,color)
{
	if (arr ==0)
	{
		temp=[];
		for (j=1;j<=10;j++)
		{
			for (i=1;i<=10;i++)
			{
				temp[temp.length]=[j,i];
			}	
		}
		arr = temp;
	}
	for(j=0;j<arr.length;j++)
		{
		id(InttoS(arr[j])).style.backgroundColor =color;
		}
}
function paintSingleCell(hit,color)
{
  var tempStr = hit.split(",");
  $("#L"+tempStr[0]+"\\,"+tempStr[1]).css('background-color',color);
}
function paintOpponent(array,color)
{
	if (typeof array == "string")
	{
		var str = array.slice(2,-2);
		var arrayStr = str.split("],[");
		for (i=0;i<arrayStr.length;i++)
		{
			var tempStrArr = arrayStr[i].split(",");
			$("#R"+tempStrArr[0]+"\\,"+tempStrArr[1]).css('background-color',color);
			
		}
	}
	else
	{
		for (i=0;i<array.length;i++)
		{
			$("#R"+String(array[i][0])+"\\,"+String(array[i][1])).css('background-color',color);
		}
		
	}
}
function opacityOpponentCells(array,opArg)
{
	if (typeof array == "string")
	{
		var str = array.slice(2,-2);
		var arrayStr = str.split("],[");
		for (i=0;i<arrayStr.length;i++)
		{
			var tempStrArr = arrayStr[i].split(",");
			$("#R"+tempStrArr[0]+"\\,"+tempStrArr[1]).css('opacity',opArg);
			
		}
	}
	else
	{
		for (i=0;i<array.length;i++)
		{
			$("#R"+String(array[i][0])+"\\,"+String(array[i][1])).css('opacity',opArg);
		}
		
	}
}
function onMouseDown(e)
{
	if (_isDeployed==0)
	{
		var target = e.target;
		// Parem klikk keerab laeva
		if (((target.className=='fourDep') || (target.className=='threeDep')|| 
				(target.className=='twoDep') || (target.className=='oneDep')))
		{		
			if (e.button==0)
			{
				_scroll = getScrolled();
				var loc =fixPosition(target);
				_defPos=target.parentNode;
				_dragElement = target;
				_startX = e.clientX;
				_startY = e.clientY;
				oldZIndex = target.style.zIndex;
				target.style.zIndex = 10000;
				document.onmousemove = onMouseMove;
				document.body.focus();
				var legalStatus = legalize(target.id);
				if (legalStatus[0])
				{
					paint(legalStatus[1],"#CCCCCC");
				}
				return false;
			}
			if (e.button==2)
			{
				turnShip(target);
			}
		}
	}
}
function onMouseMove(e) 
{
	_dragElement.style.left = (_offsetX + e.clientX + _scroll[0]  - _startX) + 'px';
	_dragElement.style.top = (_offsetY + e.clientY +_scroll[1]- _startY) + 'px';
}
function onMouseUp(e)
{ 
	function returnToDefaultPosition()
	{
		if (_defPos.className=="square")
		{
			var validate;
			if (_isTurned[_dragElement.id])
			{
				validate =validator(_defPos.id,_dragElement,true);
				placeShipToCell(_dragElement,_defPos,true,false);
			}
			else
			{
				validate = validator(_defPos.id,_dragElement,null);
				placeShipToCell(_dragElement,_defPos,false,false);
			}
			if (validate[0])
			{
				paint(validate[1],"red");
			}
		}
		else
		{
			_dragElement.style.position="absolute";
			$(_dragElement).appendTo($(_defPos));
		}
	}
	if (_dragElement != null) 
	{ 
		_dragElement.style.zIndex="-1";
		var id1= "#"+_dragElement.id;
		//Find the cell the ships top/left end is in
		if (_isTurned[_dragElement.id]== null)
		{
			var target= document.elementFromPoint(parseInt(_dragElement.style.left)+($(id1).width()*0.15)
				,parseInt(_dragElement.style.top)+($(id1).height()*0.50));
		}
		else
		{
			var target= document.elementFromPoint(parseInt(_dragElement.style.left)+($(id1).height()*0.50)
					,parseInt(_dragElement.style.top)+($(id1).width()*0.15));
		}
		if ((target != null) && (target.className=="square"))
		{
			var valid = validator(target.id,_dragElement,_isTurned[_dragElement.id]);
			if (valid[0]==true)
			{
				if (_isTurned[_dragElement.id]== null)
				{	
					placeShipToCell(_dragElement,target,false,false);
				}
				else
				{		
					placeShipToCell(_dragElement,target,true,false);
				}
				paint(valid[1],"red");
			}
			else
			{
				if (_isTurned[_dragElement.id]==true)
				{
					turnShip(_dragElement);
				}
				returnToDefaultPosition();
			}
		}
		else if ((target != null) && (target.className=="shipDiv"))
		{
			//Legalizes the cells under previous ship placement
			var toLegal =legalize(_dragElement.id);
			if (toLegal[0]==true)
			{				
				paint(toLegal[1],"#CCCCCC");
				if (isPositioned(_dragElement.id)==true)
					{
						removePosition(_dragElement.id);
					}
			}
			_dragElement.style.position="absolute";
			$(_dragElement).appendTo($("#"+_dragElement.id+"Wrap"));
			_dragElement.style.margin="0";
		}
		else
		{
			returnToDefaultPosition();
		}
		_dragElement.style.left=null;
		_dragElement.style.top=null;	
		_defPos = null;
		_dragElement.style.zIndex = _oldZIndex;
		document.onmousemove = null; 
		document.onselectstart = null; 
		_dragElement.ondragstart = null; 
		_dragElement = null; 	
	}
}
function onContext(e)
{
	return false;
}
 function InitDragDrop() 
{ 
	 document.onmousedown = onMouseDown;
	 document.onmouseup = onMouseUp;
	 document.oncontextmenu = onContext;
}